package net.ib.mtalk.ui.chat;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.UserBasicInfo;
import net.ib.mntalk.protocol.Session.AddMembersReq;
import net.ib.mntalk.protocol.client.Database.ReceiverList;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseFragmentActivity;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.MessageTable.MessageProperty;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.ui.ActivityResult;
import net.ib.mtalk.ui.attachment.geotag.GeotagActivity;
import net.ib.mtalk.ui.attachment.vcalendar.VCalendarListActivity;
import net.ib.mtalk.ui.attachment.vcard.VCardListActivity;
import net.ib.mtalk.ui.buddy.item.BuddyUUIDItem;
import net.ib.mtalk.ui.buddy.talk.BuddyTalkController;
import net.ib.mtalk.ui.inbox.InboxController;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.ProfileImageLoader;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.speech.RecognizerIntent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.CursorAdapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SelectBuddy extends BaseFragmentActivity implements OnClickListener{
	private Context mContext;
	private BuddyTalkController mUiController;
	private ChatController mChatController;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			
		};
	};
	private EditText searchBuddy;
	private ImageButton voice_btn;
	private Button btn_invite;
	private Button btn_cancel;
	List<BuddyUUIDItem> checkedPerson = new ArrayList<BuddyUUIDItem>();
	private long mClientViewUuidMsb;
	private long mClientViewUuidLsb;
	private ReceiverList receiverList;
	private Cursor cursor;
	private CursorAdapter mAdapter;
	private	String query_uuid = "";
	private int mChatType;
	
	private static final int REQ_CODE_VOICE_RECOGNITION = 100;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_selectbuddy);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		mContext = this;
		mUiController = new BuddyTalkController(mContext, mHandler);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle.containsKey("msb")) mClientViewUuidMsb = bundle.getLong("msb");
		if(bundle.containsKey("lsb")) mClientViewUuidLsb = bundle.getLong("lsb");
		
		receiverList = InboxDatabaseHelper.getReceiverList(mContext, mClientViewUuidMsb, mClientViewUuidLsb);
		mChatType = InboxDatabaseHelper.getChatType(mContext, mClientViewUuidMsb, mClientViewUuidLsb);
		
		for(UserBasicInfo info : receiverList.getReceiverList()){
			if(!query_uuid.equals("")){
				query_uuid += ",";
			}
			query_uuid += "'" + String.valueOf(GpbSupport.msbOf(info.getUserUuid())) + String.valueOf(GpbSupport.lsbOf(info.getUserUuid())) + "'";
		}
		searchBuddy = (EditText)findViewById(R.id.buddy_search);
		// 보이스 검색
		voice_btn = (ImageButton) findViewById(R.id.buddy_voice_btn);
		voice_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
				intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
				intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.buddy_voice_recognition));
				startActivityForResult(intent, REQ_CODE_VOICE_RECOGNITION);
			}
		});
		
		btn_invite = (Button) findViewById(R.id.btn_invite);
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_invite.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
		
		FragmentManager fm = getSupportFragmentManager();
		if(savedInstanceState == null) {
			SelectedBuddyListFragment list = new SelectedBuddyListFragment();
			fm.beginTransaction().add(R.id.buddy_talk_list, list).commit();
		}
		
		searchBuddy.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
//				cursor.requery();
//				mAdapter.notifyDataSetChanged();
//				list.mFavoriteObserver.onChange(true);
			}
		});
		
	}
	
	private class SelectedBuddyListFragment extends ListFragment{
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			setHasOptionsMenu(true);
			
			checkedPerson.clear();
			
			String selection = "(" + 
									"(" + BuddyTable.KEY_BUDDY_STATUS_TYPE + "=" + Common.BUDDY_STATUS_NORMAL + ")" + 
									" AND " + 
									"(" + "(" + BuddyTable.KEY_BUDDY_CHOSUNG + " LIKE ?) OR (" + BuddyTable.KEY_BUDDY_DISPLAYNICK + " LIKE ?)" + 
									")" + 
									" AND " + 
									"(" + BuddyTable.KEY_BUDDY_UUID_MSB + "||" + BuddyTable.KEY_BUDDY_UUID_LSB + " NOT IN (" + query_uuid + "))"	+ 
								")";
			MTalkLogWriter.d(selection);
			String selectionArgs[] = {"%" + searchBuddy.getText().toString() + "%", "%" + searchBuddy.getText().toString() + "%"};
			String sortOrder = BuddyTable.KEY_BUDDY_DISPLAYNICK + " COLLATE LOCALIZED ASC";
			
			ListView listView = getListView();
			
			LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			View headerView1 = inflater.inflate(R.layout.list_item_buddy_talk_group, null, true);
			headerView1.findViewById(R.id.buddy_group_chk).setVisibility(View.GONE);
			((TextView)headerView1.findViewById(R.id.buddy_group_name)).setText(getString(R.string.chat_chatting_list_now));
			((TextView)headerView1.findViewById(R.id.buddy_group_participants)).setText("("+ receiverList.getReceiverCount() + ")");
			listView.addHeaderView(headerView1);
			
			for(int i=0; i < receiverList.getReceiverCount() ; i++){
				UserBasicInfo info = receiverList.getReceiver(i);
				View headerView2 = inflater.inflate(R.layout.list_item_buddy_talk_child, null, true);
				((TextView)headerView2.findViewById(R.id.buddy_child_name)).setText(info.getDisplayName());
				headerView2.findViewById(R.id.buddy_child_check).setVisibility(View.GONE);
				headerView2.findViewById(R.id.buddy_birthday_img).setVisibility(View.GONE);
				ProfileImageLoader.getInstance(mContext).loadProfileImage((ImageView)headerView2.findViewById(R.id.buddy_child_profile), 
						GpbSupport.UuidMsgToString(info.getUserUuid()));
				listView.addHeaderView(headerView2);
			}
			
			cursor = mContext.getContentResolver().query(BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, selection, selectionArgs, sortOrder);
			
			mAdapter = new SelectBuddyCursorAdapter(mContext, cursor, 0, checkedPerson);
			setListAdapter(mAdapter);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_invite:
			if(mChatType == Common.ONE_TO_ONE && checkedPerson.size() > 1 && receiverList != null){
				InboxController controller = new InboxController(mContext, mHandler);
				controller.startInviteGroupChat(checkedPerson, receiverList);
			}else{
				if(checkedPerson.size() < 1){
					Toast.makeText(mContext, getString(R.string.chat_invite_choose_anyone), Toast.LENGTH_SHORT).show();
				} else {
					Intent intent = new Intent();
					intent.putParcelableArrayListExtra(ChatListActivity.INVITE_PERSON, (ArrayList<BuddyUUIDItem>) checkedPerson);
					setResult(RESULT_OK, intent);
					finish();
				}
			}
			// checkedPerson에 선택된 사람이 있음.
			break;
		case R.id.btn_cancel:
			checkedPerson.clear();
			mAdapter.notifyDataSetChanged();
//			finish();
			break;
		default:
			break;
		}
	}

	/**
	 * onActivityResult() 는 이 인자 세트를 세팅한 후 즉시 종료해야 한다.
	 * onResume() 마지막에서는 이 정보를 이용하여 작업을 진행한 후, 즉시 인자 세트를 폐기한다.
	 */
	ActivityResult mActivityResult = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		mActivityResult = new ActivityResult(requestCode, resultCode, intent);
	}

	/**
	 * onActivityResult() 에서 하고자 하는 작업을 이 함수에 구현한다.
	 * @param requestCode onActivityResult()에서 저장해뒀던 내용
	 * @param resultCode 위와 같음
	 * @param intent 위와 같음
	 * @see ActivityResult
	 */
	protected void handleActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case REQ_CODE_VOICE_RECOGNITION:
			ArrayList<String> matches = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			searchBuddy.setText(searchBuddy.getText() + matches.get(0));
			break;
		default:
			break;
		}
	}
	@Override
	public void onResume() {
		super.onResume();
		if (mActivityResult != null) {
			handleActivityResult(mActivityResult.getRequestCode(), mActivityResult.getResultCode(), mActivityResult.getIntent());
			mActivityResult = null;	// 반드시 있어야 함
		}
	}
}
